﻿using ExcelUnity.Exporter.Attributes;
using ExcelUnity.Exporter.Exporters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ExcelUnity.Exporter.Wrappers.SheetWrapperBuilders
{
    public static class DefaultTypeBuilder
    {
        public static ExportSheetWrapper? BuildExportSheetWrapper(ExportSheet exportSheet)
        {
            var columnProperties = CreateColumnProperties(exportSheet.DataType);
            if (columnProperties.Count == 0)
                return null;

            var exportRows = new List<ExportRowWrapper>();
            //创建title
            var rowIndex = 0;
            if (exportSheet.Title != null)
            {
                var cells = columnProperties.ConvertAll(x => new ExportCellWrapper(x.ColumnIndex, x.ColumnIndex == 0 ? exportSheet.Title.Title : string.Empty)
                {
                    MergeColumn = true,
                    CellStyle = x.ColumnIndex == 0 ? exportSheet.Title.Style : null
                });
                exportRows.Add(new ExportRowWrapper(cells, rowIndex++, exportSheet.Title.RowHeight));
            }
            var rowHeight = columnProperties.Max(t => t.RowHeight);
            //创建header
            exportRows.Add(new ExportRowWrapper(columnProperties.ConvertAll(x => new ExportCellWrapper(x.ColumnIndex, x.IsPrimaryColumn, x.Name, x.HeaderStyle)), rowIndex++, rowHeight));

            //填充行
            exportRows.AddRange(exportSheet.Data?.ConvertAll(x => new ExportRowWrapper(x, rowIndex++, columnProperties)) ?? new List<ExportRowWrapper>());

            var columns = columnProperties.ConvertAll(x => new ExportColumnWrapper(x.ColumnIndex, x.Name) { MinWidth = x.MinWidth, MaxWidth = x.MaxWidth });
            return new ExportSheetWrapper(columns, exportRows);
        }

        private static List<ColumnProperty> CreateColumnProperties(Type type)
        {
            //查询没有被忽略的字段，并且获取该字段的特性信息
            var columnProperties = type.GetProperties()
                                       .Where(x => x.GetCustomAttribute(typeof(IgnoreColumnAttribute)) is null)
                                       .Select(m => new ColumnProperty(m))
                                       .ToList();

            for (int i = 0; i < columnProperties.Count; i++)
                columnProperties[i].ColumnIndex = i;

            //设置主键列
            var mergeColumns = columnProperties.Where(x => x.MergedRowByPrimaryKey);
            //如果标注了特性MergeRowAttribute(MergedRowByPrimaryKey为true),但是列里面没有主键列，那么就将标注该特性的列设置为主键列
            if (mergeColumns.Any() && columnProperties.All(x => !x.IsPrimaryColumn))
            {
                foreach (var item in mergeColumns)
                    item.IsPrimaryColumn = true;
            }

            return columnProperties;
        }
    }
}